package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //发送验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) throws MessagingException {
        //本项目的phone一律换为了邮箱
        String phone = user.getPhone();

        //调用MailUtils中的achieveCode方法，生成验证码
        String code = MailUtils.achieveCode();

        //发送验证码
        MailUtils.sendTestMail(phone,code);

//        //将邮箱和验证码存入session中用于登录时后端进行验证
//        request.getSession().setAttribute(phone,code);

        //后续优化，将邮箱和验证码存入redis中用于登录时后端验证
        ValueOperations valueOperations = redisTemplate.opsForValue();

        //设置键为phone，值为code，存活时间为2分钟
        valueOperations.set(phone,code,2, TimeUnit.MINUTES);

        return R.success("发送验证码成功");
    }


    //登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpServletRequest request){
        //获取前端传入的Phone（这里实际上是邮箱）和code
        String phone = map.get("phone").toString();
        String code = (String) map.get("code");

//        //获取session中的code用来验证用户输入的code
//        String codeInSession = request.getSession().getAttribute(phone).toString();

        //后续优化，从redis中获取code
        ValueOperations valueOperations = redisTemplate.opsForValue();

        String codeInRedis = (String)valueOperations.get(phone);

        //看看接收到用户输入的验证码是否和redis中的验证码相同
        log.info("你输入的code{}，redis中的code{}，计算结果为{}", code, codeInRedis, (code != null && code.equals(codeInRedis)));
        if(!code.equals(codeInRedis)){
            return R.error("验证码错误");
        }

        //如果验证码验证成功
        if(code != null && code.equals(codeInRedis)){

            //判断用户是否存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            //如果不存在，就创建一个新用户
            if(user == null){
                //新创建一个user
                user = new User();
                //设置用户的邮箱以及用户名
                user.setPhone(phone);
                user.setName("用户"+code);
                //存入User表
                userService.save(user);
            }

            //存入session表示登录状态
            request.getSession().setAttribute("user",user.getId());

            //如果登录成功，则删除redis中的验证码
            redisTemplate.delete(phone);
            //返回这个用户
            return R.success(user);


        }

        return R.error("登录失败");
    }

    //登出
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){

        request.getSession().removeAttribute("user");
        return R.success("登出成功");
    }
}
